package layers.ants;

import layers.agents.PackageAgent;
import layers.agents.TruckAgent;
import layers.physical.Crossroad;
import layers.physical.Path;
import layers.physical.Road;
import exceptions.roadBlockedException;

/**
 * @author Thomas
 *
 */
public class IntentionAnt extends PathAnt{

	public IntentionAnt(Crossroad crossroad, TruckAgent truckAgent, Path path){
		super(crossroad, truckAgent, path);
		if(path == null)
			this.die();
	}

	/**
	 * - Follow path
	 * - if at dest, deliver intention
	 */
	@Override
	public void processAntTick() {
		try{
			followPath();
		}catch(roadBlockedException e){
			((TruckAgent) this.getAgent()).rejectIntention(this.getPath().getClone().reset());
			this.die();
		}
		if(!this.getPath().hasNext()){
			PackageAgent pa = this.getCrossroad().getPackageAgent();
			if(this.getCrossroad().hasPackage()){
				if(pa.processIntention(this)){
					((TruckAgent) this.getAgent()).confirmIntention(this.getPath().reset());
					this.die();
				}else{
					((TruckAgent) this.getAgent()).rejectIntention(this.getPath().getClone().reset());
					this.die();
				}
			}else{
				((TruckAgent) this.getAgent()).rejectIntention(this.getPath().getClone().reset());
				this.die();
			}
		}	
	}

	protected void followPath() throws roadBlockedException {
		if(!this.getPath().hasNext()){
			return;
		}
		Crossroad current = this.getPath().getCurrent();
		Crossroad next = this.getPath().getNext();
		Road nextRoad = current.getConnectionTo(next);
		if(nextRoad.isBlocked())
			throw new roadBlockedException();
		else
			this.getPath().increaseIndex();


		this.setCrossroad(next);
	}

	public long getTotalDistance() {
		return this.getPath().getTotalDistance();
	}
}
